package genCodeUtil.genRealize;

import genCodeUtil.util.ValidateUtils;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : Simon
 * @date : 2020/4/7
 */
public class GenModel extends BaseInit {

    public void genCode(String tableName, String modelName) {
        Context initConfig = initConfig(tableName, modelName);
        List<String> warnings = null;
        MyBatisGenerator generator = null;
        try {
            Configuration cfg = new Configuration();
            cfg.addContext(initConfig);
            cfg.validate();

            DefaultShellCallback callback = new DefaultShellCallback(true);
            warnings = new ArrayList<String>();
            generator = new MyBatisGenerator(cfg, callback, warnings);
            generator.generate(null);
        } catch (Exception e) {
            throw new RuntimeException("Model 和  Mapper 生成失败!", e);
        }

        if (generator == null || generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
            throw new RuntimeException("Model 和  Mapper 生成失败, warnings: " + warnings);
        }

        if (ValidateUtils.isNull(modelName)) {
            modelName = tableNameConvertUpperCamel(tableName);
        }
        System.out.println("Model生成成功");
        System.out.println("Mapper生成成功");
        System.out.println("XML生成成功");
    }
}
